package cn.edu.buaa.sei.jdat.io;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class JarLoader {
	
	private String downloadDir = "";
	
	public JarLoader() {
	}
	
	public File load(String url) throws IOException {
		// step 1 : parse the given URL, and ensure that it's a URL direct to Jar.
		// step 2 : download Jar into tempDir.
		// step 3 : return Jar, or wrap the local URL to a File object.
		
		// contract:
		// if the url begins with "http://", then it's a remote address;
		// otherwise it's local path+file name.
		
		if (url.startsWith("http://")) {
			FileDownloader downloader = new FileDownloader(new URL(url), downloadDir);
			downloader.run(); // TODO: run in a new thread
			if (downloader.getStatus() == FileDownloader.ERROR) {
				throw new IOException("download error");
			}
			return new File(downloader.getLocalFilePath());
		} else {
			return new File(url);
		}
	}
	
	public void setDownloadDir(String dir) {
		this.downloadDir = dir;
	}

}
